/*
 * Copyright 2010 Kevin L'Huillier <klhuillier@gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.lhuillier.pwsafe.io;


import org.lhuillier.pwsafe.Version;
import org.lhuillier.pwsafe.io.v3.V3DbWriter;
import org.lhuillier.pwsafe.model.Database;
import com.google.inject.Inject;


class DbWriterImpl implements DbWriter {
    private final V3DbWriter v3Writer;

    @Inject
    DbWriterImpl(V3DbWriter v3Writer) {
        this.v3Writer = v3Writer;
    }

    @Override
    public byte[] write(Database db, StretchedKey key) {
        if (dbVersion(db) == 3) {
            return v3Writer.write(db, key);
        }
        throw new IllegalArgumentException(
                "Only version 3 databases can be written");
    }

    private int dbVersion(Database db) {
        Short version = db.getVersion();

        if (version == null) {
            version = Version.DB_IMPL;
            db.setVersion(version);
        }

        return version / 0x100;
    }
}
